//
//  NYEditViewController.m
//  Nooryes
//
//  Created by baken on 2020/3/1.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYEditViewController.h"
#import "NYEditViewModel.h"
//#import "PhotoBrowseViewController.h"
#import "TZImagePickerController.h"
#import "NYAlertView.h"
#import "SexPickerTool.h"
#import "DatePickerTool.h"
#import "AccountModel.h"
#import "RegionPickerTool.h"
#import "NYRegionListModel.h"
@interface NYEditViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *avatar;
@property (weak, nonatomic) IBOutlet UITextView *textField;
@property (weak, nonatomic) IBOutlet UILabel *nickName;
@property (weak, nonatomic) IBOutlet UILabel *myID;
@property (weak, nonatomic) IBOutlet UILabel *gender;
@property (weak, nonatomic) IBOutlet UILabel *birthday;
@property (weak, nonatomic) IBOutlet UILabel *city;

@property (nonatomic, strong) NYEditViewModel *editVM;

@end

@implementation NYEditViewController

-(NYEditViewModel *)editVM{
    if (!_editVM) {
        _editVM = [NYEditViewModel new];
    }
    return _editVM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textField.layer.borderColor = UIColorFromRGB(0xeaeaea).CGColor;
    self.textField.layer.borderWidth = 0.5;
    self.textField.layer.masksToBounds = YES;
    self.textField.layer.cornerRadius = 5;
    
    self.editVM.selectedSex = myDelegate.account.sex;
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:myDelegate.account.image] placeholderImage:[UIImage imageNamed:@"logo_g"]];
    self.nickName.text = myDelegate.account.nickname;
    if (myDelegate.account.sex == 0) {
        self.gender.text = @"未知";
    } else if (myDelegate.account.sex == 1) {
        self.gender.text = @"男";
    } else {
        self.gender.text = @"女";
    }
    
    self.birthday.text = myDelegate.account.birthday;
    self.myID.text = myDelegate.account.no;
    self.city.text = myDelegate.account.city;
    self.textField.text = myDelegate.account.intro;
    
    UIButton *confirm = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 40)];
    [confirm setTitle:@"完成" forState:UIControlStateNormal];
    [confirm setTitleColor:UIColorFromRGB(0xff3030) forState:UIControlStateNormal];
    [confirm addTarget:self action:@selector(modifyUserInfo) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:confirm];
    
  
}


- (IBAction)onModifyAvatar:(id)sender {
    //显示弹出框列表选择
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"上传照片"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
        //响应事件
        [self chooseCameraOrLibrary:YES];
    }];
    UIAlertAction* photoAction = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault
                                                        handler:^(UIAlertAction * action) {
        //响应事件
        [self chooseCameraOrLibrary:NO];
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
        //响应事件
        
    }];
    [alert addAction:cameraAction];
    [alert addAction:photoAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (IBAction)onModifyNickName:(id)sender {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"修改昵称" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *userNameTextField = alertVC.textFields.firstObject;
        self.nickName.text = userNameTextField.text;
        self.editVM.userName = self.nickName.text;
    }]];
    [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = myDelegate.account.nickname;
        textField.textColor = UIColorFromRGB(0xbbbbbb);
    }];
    
    [self presentViewController:alertVC animated:true completion:nil];
}


- (IBAction)onModifyID:(id)sender {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"修改我的ID" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *userNameTextField = alertVC.textFields.firstObject;
        self.myID.text = userNameTextField.text;
    }]];
    [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入新ID";
        textField.textColor = UIColorFromRGB(0xbbbbbb);
    }];
    
    [self presentViewController:alertVC animated:true completion:nil];
}

- (IBAction)onModifyGender:(id)sender {
    SexPickerTool *sexPick = [[SexPickerTool alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-300, self.view.frame.size.width, 300) andSelectedRow:myDelegate.account.sex];
    __block SexPickerTool *blockPicker = sexPick;
    sexPick.callBlock = ^(NSInteger pickDate) {
        if (pickDate != 99) {
            if (pickDate == 0) {
                self.gender.text = @"未知";
            } else if (pickDate == 1) {
                self.gender.text = @"男";
            } else {
                self.gender.text = @"女";
            }
            self.editVM.selectedSex = pickDate;
        }
        
        [blockPicker removeFromSuperview];
    };
    [self.view addSubview:sexPick];
}

- (IBAction)onModifyBirthday:(id)sender {
    DatePickerTool *datePicker = [[DatePickerTool alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-300, self.view.frame.size.width, 300)];
    __block DatePickerTool *blockPick = datePicker;
    datePicker.callBlock = ^(NSString *pickDate) {
        if (pickDate) {
            self.birthday.text = pickDate;
            self.editVM.userBirthday = self.birthday.text;
        }
        [blockPick removeFromSuperview];
    };
    [self.view addSubview:datePicker];
}

- (IBAction)onModifyRegion:(id)sender {
    self.editVM.parentid = @"0";
      self.editVM.level = @"1";
      [self.editVM getRegionWithCompletionHandle:^(NSError *error) {
          if (!error && self.editVM.provinceArray.count >0) {
              RegionListModel *model =self.editVM.provinceArray[0];
              self.editVM.parentid = model.regionid;
              self.editVM.level = @"2";
              [self.editVM getRegionWithCompletionHandle:^(NSError *error) {
                  
                  RegionPickerTool *regionPicker = [[RegionPickerTool alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-300, self.view.frame.size.width, 300) andProvinceArray:self.editVM.provinceArray andCityArray:self.editVM.cityArray];

                   __block RegionPickerTool *blockPick = regionPicker;
                   regionPicker.confirmBlock = ^(NSString *pickRegion) {
                       if (pickRegion) {
                           self.city.text = pickRegion;
                           self.editVM.userCity = self.city.text;
                       }
                       [blockPick removeFromSuperview];
                   };
                   __weak RegionPickerTool *weakPicker = regionPicker;
                   regionPicker.provinceBlock = ^(NSString *parentid) {
                       self.editVM.level = @"2";
                       self.editVM.parentid = parentid;
                       [self.editVM getRegionWithCompletionHandle:^(NSError *error) {
                           weakPicker.cityArray = self.editVM.cityArray;
                       }];
                   };
                   [self.view addSubview:regionPicker];
              }];
          }
      }];
 
}

-(void)modifyUserInfo{
    self.editVM.userDesc = self.textField.text;
    
    //    self.editVM.userID = self.myID.text;
    [self.editVM modifyUserInfoWithCompletionHandle:^(NSError *error) {
        NYAlertView *alert = [NYAlertView sharedAlertView];
        if (!error) {
            alert.title = @"修改完成";
            [alert showAlert:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        } else {
            alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
            [alert showAlert:^{
            }];
        }
    }];
}


#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    CGSize size = CGSizeMake(kScreenWidth , kScreenWidth);
    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸 (打开图片后 系统取景框的大小)
    [image drawInRect:CGRectMake(0, 0, kScreenWidth, kScreenWidth)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self updateImage:scaledImage];
    self.avatar.image = image;
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


-(void)chooseCameraOrLibrary:(BOOL)isCamera{
    if (isCamera) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.allowsEditing = YES;
        picker.delegate = self;
        picker.view.frame = [[UIScreen mainScreen] bounds];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.showsCameraControls  = YES;
        [self presentViewController:picker animated:YES completion:^{
        }];
    } else {
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            if (photos.count>0) {
                [self updateImage:photos[0]];
                
            }
            
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    UIViewController *destination = segue.destinationViewController;
    if ([destination respondsToSelector:@selector(setPhone:)]) {
        
        [destination setValue:self.phone forKey:@"phone"];
    }
}

-(void)updateImage:(UIImage *)image{
    self.editVM.image = image;
    [self.editVM modifyAvatarWithCompletionHandle:^(NSError *error) {
        if (!error) {
            self.avatar.image = image;
        }else {
            NYAlertView *alert =[[NYAlertView alloc] init];
            alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
            [alert showAlert:^{
            }];
        }
    }];
}

@end
